import axios from 'axios'
import store from '../store'

// 添加响应拦截器
axios.interceptors.response.use(
  function(response) {
    // 在发送请求判断登录session是否失效
    if (response.data && response.data.errcode) {
      if (parseInt(response.data.errcode) === 40001) {
        // 未登录
        store.commit('setSessionInvalid', true)
      } else {
        store.commit('setSessionInvalid', false)
      }
    }
    return response
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 通用方法
export const POST = (url, params) => {
  return axios.post(url, params).then(res => res.data)
}

export const GET = (url, params) => {
  return axios.get(url, { params: params }).then(res => res.data)
}

export const PUT = (url, params) => {
  return axios.put(url, params).then(res => res.data)
}

export const DELETE = (url, params) => {
  return axios.delete(url, { params: params }).then(res => res.data)
}

export const PATCH = (url, params) => {
  return axios.patch(url, params).then(res => res.data)
}
